package org.stream;

import org.entity.Employee;
import org.junit.jupiter.api.Test;

import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Description
 * @Author wjj
 * @Date 2023/4/17 23:24
 */
public class CollectToMap {
//    toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper)
//    toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper, BinaryOperator<U> mergeFunction)
//    toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper, BinaryOperator<U> mergeFunction, Supplier<M>  mapSupplier)

    @Test
    public void collectToMap(){
        Map<Long, String> idToNameMap = Employee.persons().stream()
                .collect(Collectors.toMap(Employee::getId, Employee::getName));
        System.out.println(idToNameMap);
    }

    @Test
    public void collectToMap2(){
        Map<Employee.Gender, String> idToNameMap = Employee.persons().stream()
                .collect(Collectors.toMap(Employee::getGender,
                        Employee::getName,
                        (oldValue,newValue)->String.join(",",oldValue,newValue)));
        System.out.println(idToNameMap);
    }

    @Test
    public void collectToMap3(){
        Map<Employee.Gender, Long> idToNameMap = Employee.persons().stream()
                .collect(Collectors.toMap(Employee::getGender,
                        p->1L,
                        (oldValue,newValue)->oldValue+newValue));
        System.out.println(idToNameMap);
    }

    @Test
    public void collectToMap4(){
        Map<Employee.Gender, Employee>  highestEarnerByGender = Employee.persons()
                .stream()
                .collect(Collectors.toMap(Employee::getGender, Function.identity(),
                        (oldPerson, newPerson)  -> newPerson.getIncome() > oldPerson.getIncome() ? newPerson : oldPerson));
        System.out.println(highestEarnerByGender);
    }

    @Test
    public void collectToMap5(){
        Map<Long, Employee> longEmployeeMap = Employee.persons()
                .stream()
                .collect(Collectors.toMap(Employee::getId, Function.identity(),
                        (oldPerson, newPerson) -> newPerson));
        System.out.println(longEmployeeMap);
    }
}
